<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <script>
        /**
    * // Definition for a Node.
    * function Node(val, left, right, next) {
    *    this.val = val === undefined ? null : val;
    *    this.left = left === undefined ? null : left;
    *    this.right = right === undefined ? null : right;
    *    this.next = next === undefined ? null : next;
    * };
    */

        /**
         * @param {Node} root
         * @return {Node}
         */


        var connect = function (root) {
            const func = function (root) {
                if (!root) {
                    return;
                }
                let arr = new Array();
                arr[0] = root;
                while (arr.length > 0) {
                    let size = arr.length;
                    for (let i = 0; i < size; i++) {
                        let temp = arr.shift();
                        if (i < size - 1) {
                            temp.next = arr[0];
                        }
                        if (temp.left !== null) {//说明不是子节点
                            arr.push(temp.left);
                            arr.push(temp.right);
                        }

                    }
                }
                console.log('root',root)
            }
            func(root);

            return root;
        };
        
        let root = {
            val: 1,
            left: {
                val: 2,
                left: { val: 4, left: null, right: null, next: null },
                right: { val: 5, left: null, right: null, next: null },
                next: null
            },
            right: {
                val: 3,
                left: { val: 6, left: null, right: null, next: null },
                right: { val: 7, left: null, right: null, next: null },
                next: null
            },
            next: null
        };
        connect(root);
    </script>
</body>

</html>